<?php

/**
 * 修复 由于商品被删除 或删除之后再恢复 造成的用户收藏商品计数器不准确问题
 *
 **/

use Biz\model\ShopFavorite;
use Biz\model\wiki\Wiki;
use Doraemon\cache\UserCounter;
use Doraemon\tools\Log;
use Medoo\Medoo;

ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

//查询所有已删除的wiki_id
$startTime = time();
$startSelectShopTime = time();
$delWikiArr = Wiki::selectByWhere(['status' => Wiki::STATUS_DEL], 'id');
echo '被删除商品查询完成,消耗时长'.(time() - $startSelectShopTime).PHP_EOL;
//更新所有已收藏商品的用户 fav_spu 计数器
$where['obj_type'] = ShopFavorite::TYPE_WIKI;//只查询商品类型的收藏数据
$count = ShopFavorite::get(['cnt' => Medoo::raw('count(distinct(uid))')], $where);
$count = $count['cnt'] ?? 0;
$pageSize = 50000;
$pageAll = ceil($count / $pageSize);
$page = 1;
try {
    while ($page <= $pageAll) {
        if ($delWikiArr) {
            $where['obj_id[!]'] = $delWikiArr;//过滤已被删除的wiki_id
        }
        $where['obj_type'] = ShopFavorite::TYPE_WIKI;//只查询商品类型的收藏数据
        $where['status'] = ShopFavorite::STATUS_NORMAL;//收藏状态正常
        $where['GROUP'] = 'uid';//根据uid分组
        $where['ORDER'] = 'id';//根据id排序
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        echo '这是第'.($page).'批数据处理开始'.PHP_EOL;
        $result = ShopFavorite::select(['cnt' => Medoo::raw('count(uid)'), 'uid'], $where);
        var_dump(ShopFavorite::log());
        if ($result) {
            foreach ($result as $item) {
                //重置 fav_spu 计数器
//                UserCounter::setMuti($item['uid'], [UserCounter::TYPE_FAVORITE_SPU => $item['cnt']]);

            }
        }

        echo '这是第'.($page).'批数据处理结束'.PHP_EOL;
        Log::info('这是第'.$page.'批数据处理结束');
        $page++;
    }
} catch (Exception $exception) {
    Log::info('UserCounter fav_spu 计数器数据修复失败', ['exception' => $exception]);
}

// 已经删除的商品 对应的用户 更新计数器 （比如某个用户 只收藏了1个商品 但是这个商品被删除了）
$uidArr = ShopFavorite::select('uid', ['obj_id' => $delWikiArr, 'obj_type' => ShopFavorite::TYPE_WIKI]);
if ($uidArr) {
    $startSetCounter = time();

    $where['obj_id[!]'] = $delWikiArr;//过滤已被删除的wiki_id
    $where['uid'] = $uidArr;
    $where['obj_type'] = ShopFavorite::TYPE_WIKI;//只查询商品类型的收藏数据
    $where['status'] = ShopFavorite::STATUS_NORMAL;//收藏状态正常
    $where['GROUP'] = 'uid';//根据uid分组
    $result = ShopFavorite::select(['cnt' => Medoo::raw('count(uid)'), 'uid'], $where);
    if ($result) {
        foreach ($result as $item) {
            //重置 fav_spu 计数器
//            UserCounter::setMuti($item['uid'], [UserCounter::TYPE_FAVORITE_SPU => $item['cnt']]);
        }
    }
    echo '重置计数器完成，耗时：'.(time() - $startSetCounter).PHP_EOL;
}
echo 'success'.PHP_EOL;
echo '总共耗时：'.(time() - $startTime).PHP_EOL;



